package faceb.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import com.mysql.fabric.xmlrpc.base.Array;

import faceb.server.dao.NewspicDao;
import faceb.server.model.NewsPic;
import faceb.server.util.MyBatisUtil;
import faceb.server.util.ServerFinal;

@Repository("newspicDao")
public class NewspicDaoImpl implements NewspicDao {
	private SqlSessionFactory factory = MyBatisUtil.getsqlSessionFactory();

	public int insertNewspic(NewsPic newspic) {
		SqlSession session = factory.openSession();
		int result = session.insert("NewsPicMapper.insertNewspic", newspic);
		session.commit();
		session.close();
		return result;
	}

	public List<NewsPic> getNewspicByNewsId(String newsid) {
		SqlSession session = factory.openSession();
		List<NewsPic> newspics = session.selectList(
				"NewsPicMapper.getNewpicByNewsId", newsid);
		session.close();
		newspics = ReplaceNewsPicListUrl(newspics);
		return newspics;
	}

	public NewsPic getNewspicByPicId(String newspicId){
		SqlSession session = factory.openSession();
		NewsPic newspic = session.selectOne(
				"NewsPicMapper.getNewpicByNewspicId", newspicId);
		session.close();
		newspic = ReplaceNewsPicUrl(newspic);
		return newspic;
	}
	public static void main(String[] args) {
		NewsPic newspic = new NewspicDaoImpl()
				.getNewspicByPicId("d4f690fede4a421c8924f9ac3a105de2");
		System.out.println(newspic);
	}
	
	private NewsPic ReplaceNewsPicUrl(NewsPic pic){
		String url = pic.getNp_path();
		url = url.replaceFirst("http://.+:*[0-9]*/faceb-cupt/", ServerFinal.SERVER_URL);
		pic.setNp_path(url);
		return pic ;
	}
	
	private List<NewsPic> ReplaceNewsPicListUrl(List<NewsPic> pics){
		List<NewsPic> pics2 = new ArrayList<NewsPic>();
		for (NewsPic pic :pics) {
			NewsPic pic2=ReplaceNewsPicUrl(pic);
			pics2.add(pic2);
		}
		return pics2;
	}
}
